package com.zhou.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zhou.constant.MessageConstant;
import com.zhou.dao.*;
import com.zhou.entity.PageResult;
import com.zhou.entity.QueryPageBean;
import com.zhou.entity.Result;
import com.zhou.pojo.*;
import com.zhou.service.OrderListService;
import com.zhou.service.SetmealService;
import com.zhou.utils.DateUtils;
import com.zhou.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = OrderListService.class)
@Transactional
@Component
public class OrderListServiceImpl implements OrderListService {
    @Autowired
    private OrderListMapper orderListMapper;

    @Autowired
    private OrderSettingMapper orderSettingMapper;

    @Autowired
    private MemberMapper memberDao;

    @Autowired

    private MapDao mapDao;

    @Autowired
    private SetmealMapper setmealDao;

    @Autowired
    private MemberUploadDao memberUploadDao;

    @Override
    public PageResult pageQuery(Integer currentPage, Integer pageSize, String queryString) {
        PageHelper.startPage(currentPage,pageSize);
        Page<Map> orderlist = orderListMapper.pageQuery(queryString);
        return new PageResult(orderlist.getTotal(), orderlist.getResult());
    }

    @Override

    public Result order(Map map) throws Exception {
// 0、判断预约的地址是否是正确的  返回的公司地址对应的id
       int addressId;
         try {
            addressId = mapDao.findCountByAddressName((String) map.get("companyAddress"));
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SELECTED_ADDRESS_FAIL);
        }

        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        String orderDate = (String) map.get("orderDate");//预约日期
        OrderSetting orderSetting = orderSettingMapper.findByOrderDate(DateUtils.parseString2Date(orderDate));
        if (orderSetting == null) {
            //指定日期没有进行预约设置，无法完成体检预约
            return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
        }
        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        int number = orderSetting.getNumber();//可预约人数
        int reservations = orderSetting.getReservations();//已预约人数
        if (reservations >= number) {
            //已经约满，无法预约
            return new Result(false, MessageConstant.ORDER_FULL);
        }
        //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        String telephone = (String) map.get("telephone");//获取用户页面输入的手机号
        Member member = memberDao.findByTelephone(telephone);
        if (member != null) {
            //判断是否在重复预约
            Integer memberId = member.getId();//会员ID
            Date order_Date = DateUtils.parseString2Date(orderDate);//预约日期
            String setmealId = (String) map.get("setmealId");//套餐ID
            Order order = new Order(memberId, order_Date, Integer.parseInt(setmealId));
            //根据条件进行查询
            List<Order> list = orderListMapper.findByCondition(order);
            if (list != null && list.size() > 0) {
                //说明用户在重复预约，无法完成再次预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        } else {
            //4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
            member = new Member();
            member.setFileNumber(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));//档案号
            member.setName((String) map.get("name"));
            member.setPassword(MD5Utils.md5("123456"));//设置默认密码123456
            member.setPhoneNumber(telephone);
            member.setIdCard((String) map.get("idCard"));
            member.setSex((String) map.get("sex"));
            member.setBirthday(DateUtils.parseString2Date((String) map.get("birthday")));
            member.setRegTime(new Date());
            memberDao.add(member);//自动完成会员注册

        }

//5、预约成功，更新当日的已预约人数

        Order order = new Order();

        order.setMemberId(member.getId());//设置会员ID
        order.setOrderDate(DateUtils.parseString2Date(orderDate));//预约日期
        order.setOrderType((String) map.get("orderType"));//预约类型
        order.setOrderStatus(Order.ORDERSTATUS_NO);//到诊状态
        order.setSetmealId(Integer.parseInt((String) map.get("setmealId")));//套餐ID
        order.setAddressId(addressId);
        orderListMapper.add(order);
        //更新已预约人数
        orderSetting.setReservations(orderSetting.getReservations() + 1);//设置已预约人数+1
        orderSettingMapper.editReservationsByOrderDate(orderSetting);

        this.addMemberFileReport(member, order);
        return new Result(true, MessageConstant.ORDER_SUCCESS, order.getId());
    }

    /**
     * 添加体检报告
     *
     * @param member
     * @param order
     */
    public void addMemberFileReport(Member member, Order order) {
        MemberFileReport memberFileReport = new MemberFileReport();
        memberFileReport.setFileNumber(member.getFileNumber());//档案号
        memberFileReport.setName(member.getName());//姓名
        memberFileReport.setSex(member.getSex());//性别
        memberFileReport.setPhoneNumber(member.getPhoneNumber());//手机号
        memberFileReport.setCheckuptime(order.getOrderDate());//体检日期

        Setmeal setmeal = setmealDao.findById(order.getSetmealId());
        memberFileReport.setSetmealId(order.getSetmealId());//套餐ID
        memberFileReport.setSetmealName(setmeal.getName());//套餐名称
        memberFileReport.setFilestatus("0");//报告状态
        memberUploadDao.add(memberFileReport);

    }

    /**
     * 根据预约ID查询预约相关信息（体检人姓名、预约日期、套餐名称、预约类型）
     */
    @Override
    public Map findById(Integer id) throws Exception {
        Map map = orderListMapper.findById4Detail(id);
        if (map != null) {
            //处理日期格式
            Date orderDate = (Date) map.get("orderDate");
            map.put("orderDate", DateUtils.parseDate2String(orderDate));
        }
        return map;
    }

    @Override
    public Result edit(Order order) {
        try {
            //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
            OrderSetting orderSetting = orderSettingMapper.findByOrderDate(order.getOrderDate());
            if (orderSetting == null) {
                //指定日期没有进行预约设置，无法完成体检预约
                return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
            }
            //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
            int number = orderSetting.getNumber();//可预约人数
            int reservations = orderSetting.getReservations();//已预约人数
            if (reservations >= number) {
                //已经约满，无法预约
                return new Result(false, MessageConstant.ORDER_FULL);
            }
            //通过map来获取预约信息
            Map map = orderListMapper.findById(order.getId());
        //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        Member member = memberDao.findById(order.getMemberId());
        if (member != null) {
            //判断是否在重复预约
            Integer memberId = member.getId();//会员ID
            Date newOrderDate = order.getOrderDate();//新预约日期

            Integer setmealId = order.getSetmealId();//套餐ID
            Integer addressId = order.getAddressId();//地址ID
            Order order1 = new Order(memberId, newOrderDate, setmealId);
            //根据条件进行查询
            List<Order> list = orderListMapper.findByCondition(order1);
            if (list != null && list.size() > 1) {
                //说明用户在重复预约，无法完成再次预约
                return new Result(false, MessageConstant.HAS_ORDERED);
            }
        }
        //4.获取老的预约的时间
        Date oldOrderDate = (Date) map.get("orderDate");//老预约日期
        OrderSetting oldOrderSetting = orderSettingMapper.findByOrderDate(oldOrderDate);

        //修改体检中心数据
        MemberFileReport memberFileReport = new MemberFileReport();
        memberFileReport.setName((String) map.get("member"));
        memberFileReport.setSetmealId((Integer) map.get("setmealId"));
        memberFileReport.setSetmealName((String) map.get("setmeal"));
        memberFileReport.setCheckuptime(oldOrderDate);
        MemberFileReport idByInformation = memberUploadDao.findIdByInformation(memberFileReport);

        MemberFileReport memberFileReport01 = new MemberFileReport();
        memberFileReport01.setId(idByInformation.getId());
        memberFileReport01.setName((String) map.get("member"));
        memberFileReport01.setSetmealId(order.getSetmealId());
        Setmeal setmeal = setmealDao.findById(order.getSetmealId());
        memberFileReport01.setSetmealName(setmeal.getName());//套餐名称
        memberFileReport01.setCheckuptime(order.getOrderDate());
        memberUploadDao.edit3Information(memberFileReport01);

        //5、预约成功，更新当日的已预约人数
            orderListMapper.edit(order);


        //预约时间 是否相同 相同仅仅修改数据库状态
        if (oldOrderDate.equals(order.getOrderDate())) {
            orderSettingMapper.editReservationsByOrderDate(orderSetting);
        } else {
            //更新已预约人数
            orderSetting.setReservations(orderSetting.getReservations() + 1);//设置已预约人数+1
            oldOrderSetting.setReservations(oldOrderSetting.getReservations() - 1);//设置老日期已预约人数-1
            orderSettingMapper.editReservationsByOrderDate(orderSetting);
            orderSettingMapper.editReservationsByOrderDate(oldOrderSetting);
        }

        return new Result(true, MessageConstant.EDIT_ORDERLIST_SUCCESS);
    } catch (Exception e) {
        e.printStackTrace();
        return new Result(false, MessageConstant.EDIT_ORDERLIST_FAIL);
    }
    }

    /**
     * 删除预约订单
     *
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        //通过map来获取预约信息
        Map map = orderListMapper.findById(id);
        Date orderDate = (Date) map.get("orderDate");
        //检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        OrderSetting orderSetting = orderSettingMapper.findByOrderDate(orderDate);

        orderSetting.setReservations(orderSetting.getReservations() - 1);//设置已预约人数-1
        orderSettingMapper.editReservationsByOrderDate(orderSetting);

        orderListMapper.deleteById(id);

        //删除体检中心数据
        MemberFileReport memberFileReport = new MemberFileReport();
        memberFileReport.setName((String) map.get("member"));
        memberFileReport.setSetmealName((String) map.get("setmeal"));
        memberFileReport.setPhoneNumber((String) map.get("telephone"));
        memberFileReport.setSex((String) map.get("sex"));
        memberFileReport.setCheckuptime(orderDate);
        System.out.println(memberFileReport);
        memberUploadDao.deleteByMember(memberFileReport);
    }
}
